package br.com.tiespec.ejb.Dao;

import java.io.Serializable;

import javax.ejb.EJB;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.tiespec.ejb.Ejb.HibernateSingleton;
import br.com.tiespec.model.Enum.TipoSortOrder;
import br.com.tiespec.model.Modelo.EntidadeGenerica;
import br.com.tiespec.model.Util.DAOException;

public class DAO implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	Session session;
	Transaction tx;
	
	@EJB
	HibernateSingleton singleton;
	
	void begin(){
		this.session = singleton.getSession();
		this.tx = this.session.beginTransaction();
	}
	
	void commit(){
		this.tx.commit();
	}
	
	void fecharConexao(){
		try {
			if (this.tx.isActive())
				this.tx.rollback();
			if (this.session.isOpen())
				this.session.close();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public void save(EntidadeGenerica object) throws DAOException {
		try {
			begin();
			this.session.save(object);
			commit();
			fecharConexao();
		} catch (Exception e) {
			fecharConexao();
			throw new DAOException(e);
		}
	}
	
	public void update(EntidadeGenerica object) throws DAOException {
		try {
			begin();
			this.session.update(object);
			commit();
			fecharConexao();
		} catch (Exception e) {
			fecharConexao();
			throw new DAOException(e);
		}
	}
	
	public void delete(Class<?> klass, Long id) throws DAOException {
		try {
			begin();
			this.session.delete(this.session.createCriteria(klass)
					.add(Restrictions.eq("id", id)).uniqueResult());
			commit();
			fecharConexao();
		} catch (Exception e) {
			fecharConexao();
			throw new DAOException(e);
		}
	}
	
	Criteria montaPaginacaoSimples(Criteria criteria, int first, int pageSize, 
			String sortField, TipoSortOrder sortOrder){
		criteria.setFirstResult(first);
		criteria.setMaxResults(pageSize);
		if (sortField != null) {
			String[] sortFields;
			sortFields = sortField.split("[/.]");
			Criteria criteriaSortFields = criteria;
			int x;
			// length -1 porque o último não vai passar (é campo a ser ordenado)
			for(x = 0; x < sortFields.length-1; x++){
				criteriaSortFields = criteriaSortFields.createCriteria(sortFields[x]);
			}
			if (sortOrder.equals(TipoSortOrder.DESCENDING)) {
				criteriaSortFields.addOrder(Order.desc(sortFields[x]));
			} else if (sortOrder.equals(TipoSortOrder.ASCENDING)) {
				criteriaSortFields.addOrder(Order.asc(sortFields[x]));
			}
		}
		return criteria;
	}
	
	boolean isNullOrBlank(String s){
		if (s==null || s.trim().length() == 0)
			return false;
		return true;
	}
}